<?php

namespace App\Http\Controllers\Admin;

use App;
use App\Common\Upload;
use App\Common\Status;
use App\Helper\GuzzleHttp;
use App\Http\Controllers\Controller as BaseController;
use Illuminate\Http\Request;
use App\Http\Logic\Admin\UploadLogic;
use  App\Helper\Helper;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class PushLinkFlowController extends BaseController
{


    public function createUsers()
    {
        $token = self::getToken();
        if (!$token) {
            echo "获取token失败！";
            return;
        }
        $heard["X-OpenApi-Token"] = $token;
        $heard["User-Agent"]      = "MyClient/1.0.0";
        $redis                    = Redis::connection();
        $redis->select(12);

        $page    = 1; // 当前页码
        $perPage = 2; // 每页数量

        $members    = [];
        $lastMember = null;

        do {
            $lower = ($page - 1) * $perPage; // 计算偏移量
            //            $upper = $lower + $perPage - 1; // 计算上限

            $result  = $redis->zrangebyscore("zuid", 0, 2, ["LIMIT" => ["offset" => $lower, "count" => $perPage]]);
            $members = array_merge($members, $result); // 将本次循环获取的成员添加到总列表中

            $lastMember = end($result); // 获取本次循环最后一个成员

            $page++;
        } while (!empty($result) && $lastMember !== end($members)); // 继续循环的条件是本次循环返回不为空且最后一个成员不等于已获取到的最后一个成员

        if (count($members) > 0) {
            // 输出最终获取到的所有成员
            foreach ($members as $member) {
                $data                = $identities = $messages = $messagesData = $info = $auth = [];
                $register_source     = "H5";
                $data["channelKey"]  = Status::LINK_FLOW["channel_key"];
                $data["channelType"] = Status::LINK_FLOW["channel_type"];

                # 获取 用户信息
                $info = DB::table('gz_users')->find($member);

                if ($info) {
                    if ($info->register_source == 1) {
                        //                    注册来源端口 1:微信公众号 2:微信小程序 3:pc 4:h5 5:ios 6:android 7招聘网
                        $register_source = "微信公众号";
                    } elseif ($info->register_source == 2) {
                        $register_source = "微信小程序";
                    } elseif ($info->register_source == 4) {
                        $register_source = "pc";
                    }
                    $name = $info->username ? $info->username : $info->nickname;
                    if ($info->mobile) {
                        $identities[1]["id"]   = $info->mobile;
                        $identities[1]["type"] = "mobilePhone";
                    }
                } else {
                    continue;
                }

                $auth = DB::table('gz_user_auth')->where("user_id", $member)->select(["identifier", "unionid"])->first();

                if ($auth) {
                    if ($auth->unionid) {
                        $identities[2]["id"]   = $auth->unionid;
                        $identities[2]["type"] = "wechat.unionId";
                    }

                    if ($auth->identifier) {
                        $identities[3]["id"]   = $auth->identifier;
                        $identities[3]["type"] = "wechat.openId";
                    }
                }

                # 标记完成
                if ($auth) {
                    if ($auth->unionid && $auth->identifier && $info->mobile) {
                        $redis->zAdd("zuid", 3, $info->id);
                    }
                }

                $timestamp    = microtime(true);
                $milliseconds = round(($timestamp - floor($timestamp)) * 1000);

                $messages[0]["domain"]                       = "contact";
                $messages[0]["action"]                       = "set";
                $messages[0]["ts"]                           = floor($timestamp) . $milliseconds;
                $messages[0]["data"]["name"]                 = $name;
                $messages[0]["data"]["mobilePhone"]          = $info->mobile ?: "";
                $messages[0]["data"]["utm"]["source"]        = "官网";
                $messages[0]["data"]["utm"]["medium"]        = $register_source;
                $messages[0]["data"]["props"]["eeeknowDate"] = date("Y-m-d H:i:s", $info->create_time);

                $messages[1]["domain"]            = "event";
                $messages[1]["action"]            = "track";
                $messages[1]["ts"]                = floor($timestamp) . $milliseconds;
                $messages[1]["data"]["event"]     = "EEEKNOW_REGISTER_PC";
                $messages[1]["data"]["eventDate"] = floor($timestamp) . $milliseconds;


                $data["identities"] = array_merge($identities);
                $data["messages"]   = $messages;
                Log::channel('link_flow')->info("flow发送数据 ：" . $info->id . " ：" . json_encode($data, JSON_UNESCAPED_UNICODE));
                $r = GuzzleHttp::GuzzlePostNew(Status::LINK_FLOW["url"] . "open/messages", $data, $heard, 5);
                Log::channel('link_flow')->info("flow返回状态 ：" . $info->id . " ：" . json_encode($r, JSON_UNESCAPED_UNICODE)) . PHP_EOL . PHP_EOL;

                echo $info->id . "推送成功！";
            }
        }
    }


    /**
     * 一次推送
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function disposablePush()
    {
        $token = self::getToken();
        if (!$token) {
            echo "获取token失败！";
            return;
        }
        $heard["X-OpenApi-Token"] = $token;
        $heard["User-Agent"]      = "MyClient/1.0.0";
        $redis                    = Redis::connection();
        $redis->select(12);

        $count = env("LINK_FLOW") ? env("LINK_FLOW") : 20;

        $members = Db::table('gz_users')->where([["closed", '=', 0], ["link_flow", "=", 1]])
            ->limit($count)->get();

        if ($members->isEmpty()) {
            echo "暂无数据！";
            return;
        }
        // 一次性推送 写入/修改缓存
        foreach ($members as $member) {
            $data                = $identities = $messages = $messagesData = $auth = [];
            $register_source     = "H5";
            $data["channelKey"]  = Status::LINK_FLOW["channel_key"];
            $data["channelType"] = Status::LINK_FLOW["channel_type"];

            if ($member->register_source == 1) {
                //                    注册来源端口 1:微信公众号 2:微信小程序 3:pc 4:h5 5:ios 6:android 7招聘网
                $register_source = "微信公众号";
            } elseif ($member->register_source == 2) {
                $register_source = "微信小程序";
            } elseif ($member->register_source == 4) {
                $register_source = "pc";
            }
            $name = $member->username ? $member->username : $member->nickname;
            //            $member->mobile = 13211111131;
            if ($member->mobile) {
                $identities[1]["id"]   = $member->mobile;
                $identities[1]["type"] = "mobilePhone";
            }


            $auth = DB::table('gz_user_auth')->where("user_id", $member->id)->select(["identifier", "unionid"])
                ->first();

            if ($auth) {
                if ($auth->unionid) {
                    $identities[2]["id"]   = $auth->unionid;
                    $identities[2]["type"] = "wechat.unionId";
                }

                if ($auth->identifier) {
                    $identities[3]["id"]   = $auth->identifier;
                    $identities[3]["type"] = "wechat.openId";
                }
            }

            # 标记完成
            if ($auth) {
                if ($auth->unionid && $auth->identifier && $member->mobile) {
                    $redis->zAdd("zuid", 3, $member->id);
                } else {
                    $redis->zAdd("zuid", 1, $member->id);
                }
            } elseif ($member->mobile) {
                $redis->zAdd("zuid", 1, $member->id);
            } else {
                echo "用户ID ：" . $member->id . " openid unionid 和 手机号 都不存在";
                continue;
            }

            $timestamp                                   = microtime(true);
            $milliseconds                                = round(($timestamp - floor($timestamp)) * 1000);
            $messages[0]["domain"]                       = "contact";
            $messages[0]["action"]                       = "set";
            $messages[0]["ts"]                           = floor($timestamp) . $milliseconds;
            $messages[0]["data"]["name"]                 = $name;
            $messages[0]["data"]["mobilePhone"]          = $member->mobile ?: "";
            $messages[0]["data"]["utm"]["source"]        = "官网";
            $messages[0]["data"]["utm"]["medium"]        = $register_source;
            $messages[0]["data"]["props"]["eeeknowDate"] = date("Y-m-d H:i:s", $member->create_time);

            $messages[1]["domain"]            = "event";
            $messages[1]["action"]            = "track";
            $messages[1]["ts"]                = floor($timestamp) . $milliseconds;
            $messages[1]["data"]["event"]     = "EEEKNOW_REGISTER_PC";
            $messages[1]["data"]["eventDate"] = floor($timestamp) . $milliseconds;

            $data["identities"] = array_merge($identities);
            $data["messages"]   = $messages;

            Log::channel('link_flow')->info("once flow发送数据 ：" . $member->id . " ：" . json_encode($data,
                    JSON_UNESCAPED_UNICODE));
            $r = GuzzleHttp::GuzzlePostNew(Status::LINK_FLOW["url"] . "open/messages", $data, $heard, 5);
            if ($r && $r["code"] == 200 && empty($r["contents"])) {
                $or = Db::table('gz_users')->where("id", $member->id)->update(["link_flow" => 2]);
                if ($or) {
                    echo $member->id . "推送成功！";
                }
            }
        }
    }


    /**
     * 创建订单
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function createUsersOrders()
    {
        $token = self::getToken();
        if (!$token) {
            echo "获取token失败！";
            return;
        }
        $heard["X-OpenApi-Token"] = $token;
        $heard["User-Agent"]      = "MyClient/1.0.0";

        $count = env("LINK_FLOW") ? env("LINK_FLOW") : 20;

        $orders = Db::table('gz_order')->where([["order_status", '=', 2], ["user_id", "<>", ""], ["link_flow", "=", 1]])
            ->limit($count)->get();
        //        $orders = Db::table('gz_order')->whereIn("id", [6871, 6886])
        //            ->where("link_flow", 1)
        //            ->limit(2)->get();


        if ($orders->isNotEmpty()) {
            $token  = self::getToken();
            $orders = $orders->toArray();

            // 请求头信息
            $headers["X-OpenApi-Token"] = $token;
            $headers["User-Agent"]      = "MyClient/1.0.0";

            foreach ($orders as $ks => $o) {
                $k                   = 0;
                $data                = [];
                $data["channelKey"]  = Status::LINK_FLOW["channel_key"];
                $data["channelType"] = Status::LINK_FLOW["channel_type"];
                $data["identities"]  = [];

                $timestamp                      = microtime(true);
                $milliseconds                   = round(($timestamp - floor($timestamp)) * 1000);
                $data["messages"][$k]           = [];
                $data["messages"][$k]["domain"] = "salesOrder";
                $data["messages"][$k]["action"] = "set";
                $data["messages"][$k]["ts"]     = floor($timestamp) . $milliseconds;

                $identities = $identitiesUnid = $identitiesOpenid = [];

                $info = Db::table('gz_users')->where("id", $o->user_id)->first();

                if ($info) {
                    if ($info->mobile) {
                        $identities[0]["id"]   = $info->mobile;
                        $identities[0]["type"] = "mobilePhone";
                    }
                } else {
                    echo "该用户竟然不存在？？？ ：" . $o->user_id;
                    continue;
                }
                $auth = Db::table('gz_user_auth')->where("user_id", $o->user_id)->first();

                if ($auth) {
                    if ($auth->unionid) {
                        $identitiesUnid[1]["id"]   = $auth->unionid;
                        $identitiesUnid[1]["type"] = "wechat.unionId";
                    }

                    if ($auth->identifier) {
                        $identitiesOpenid[2]["id"]   = $auth->identifier;
                        $identitiesOpenid[2]["type"] = "wechat.openId";
                    }
                }

                $mobilePhone = $checkUnionId = $checkOpenId = 0;
                $query       = ["id" => $info->mobile, "idType" => "mobilePhone"];
                # 查询用户是否存在
                $checkMobile = GuzzleHttp::GuzzleGetNew(Status::LINK_FLOW["url"] . "open/identity/contact", 2,
                    $headers, $query);
                if ($checkMobile['code'] == 200 && !empty($checkMobile['contents'])) {
                    $mobilePhone = 1;
                } else {
                    $queryUnid = ["id" => $auth->unionid, "idType" => "wechat.unionId"];
                    $checkUnid = GuzzleHttp::GuzzleGetNew(Status::LINK_FLOW["url"] . "open/identity/contact", 2, $headers,
                        $queryUnid);
                    if ($checkUnid['code'] == 200 && !empty($checkUnid['contents'])) {
                        $checkUnionId = 1;
                    } else {
                        $queryOpenid = ["id" => $auth->unionid, "idType" => "wechat.unionId"];
                        $checkOpenid = GuzzleHttp::GuzzleGetNew(Status::LINK_FLOW["url"] . "open/identity/contact", 2,
                            $headers, $queryOpenid);
                        if ($checkOpenid['code'] == 200 && !empty($checkOpenid['contents'])) {
                            $checkOpenId = 1;
                        }
                    }
                }

                if ($mobilePhone == 1) {
                    $ident = array_merge($identities);
                } else if ($checkUnionId == 1) {
                    $ident = array_merge($identitiesUnid);
                } else if ($checkOpenId == 1) {
                    $ident = array_merge($identitiesOpenid);
                } else {
                    echo "订单号：" . $o->id, '用户不存在linkflow中！';

                    Log::channel('link_flow_order')->info("订单号 ：" . $o->id . " 的用户不存在linkflow中");
                    continue;
                }

                echo '-----------------------------------------';
                $data["identities"] = $ident;

                # 订单详情
                $orderData = Db::table('gz_order')->where("id", $o->id)->first();

                $source = "H5";
                if ($orderData->source == 1) {
                    // 1:微信公众号  2:微信小程序  3:pc  4:h5
                    $source = "微信公众号";
                } elseif ($orderData->source == 2) {
                    $source = "微信小程序";
                } elseif ($orderData->source == 3) {
                    $source = "pc";
                }

                $msgData                      = [];
                $msgData["saleChannel"]       = $source;
                $msgData["orderId"]           = $orderData->order_sn;
                $msgData["orderStatus"]       = $orderData->order_status == 2 ? "TRADE_SUCCESS" : "TRADE_CLOSED";
                $msgData["payType"]           = $orderData->pay_type == 1 ? "微信" : "支付宝";
                $msgData["payDate"]           = date("Y-m-d H:i:s", $orderData->pay_time);
                $msgData["orderDate"]         = date("Y-m-d H:i:s", $orderData->create_time);
                $msgData["totalPrice"]        = $orderData->price;
                $msgData["paymentPrice"]      = $orderData->pay_price;
                $msgData["totalQuantity"]     = 1;
                $data["messages"][$k]["data"] = $msgData;


                $goodsData = Db::table('gz_goods')->where("id", $orderData->goods_id)->first();

                $goods_type = "随时学";
                if ($goodsData->goods_category == 1) {
                    //          1 训练营 2 就业班  3 大班课 4 随时学
                    $goods_type = "训练营";
                } elseif ($goodsData->goods_category == 2) {
                    $goods_type = "就业班";
                } elseif ($goodsData->goods_category == 3) {
                    $goods_type = "大班课";
                }

                $line                          = [];
                $line[$k]["lineId"]           = $orderData->id;
                $line[$k]["orderDate"]        = date("Y-m-d H:i:s", $orderData->create_time);
                $line[$k]["category"]         = $goods_type;
                $line[$k]["itemPaymentPrice"] = $orderData->pay_price;
                $line[$k]["productName"]      = $goodsData->goods_name;
                $line[$k]["itemId"]           = $goodsData->id;
                //                $data["messages"][$k]["lines"] = $line;
                $data["messages"][$k]["data"]["lines"] = $line;

                //                var_dump('=======');
                //                var_dump('=======');
                //                var_dump($data);

                Log::channel('link_flow_order')->info("flow发送订单数据数据 ：" . $o->id . " ：" . json_encode($data,
                        JSON_UNESCAPED_UNICODE));
                $r = GuzzleHttp::GuzzlePostNew(Status::LINK_FLOW["url"] . "open/messages/orders", $data, $headers);

                //                var_dump('===$r====');
                //                var_dump($r);

                # 更新
                if ($r && $r["code"] == 200 && empty($r["contents"])) {
                    Log::channel('link_flow_order')->info("推送订单状态 ：" . $o->id . " ：" . json_encode($r,
                            JSON_UNESCAPED_UNICODE));
                    $or = Db::table('gz_order')->where("id", $o->id)->update(["link_flow" => 2]);
                    if ($or) {
                        echo "订单号：" . $o->id, '更新完成！';
                    }
                } else {
                    Log::channel('link_flow_order')->info("error -data ：" . $o->id . " ：" . json_encode($r,
                            JSON_UNESCAPED_UNICODE));
                }
            }
        }

        echo "暂无数据！";
    }

    /**
     * @return mixed|string
     */
    private static function getToken()
    {
        $header["X-OpenApi-Secret"] = Status::LINK_FLOW["secret"];
        $header["X-OpenApi-Key"]    = Status::LINK_FLOW["key"];
        $header["User-Agent"]       = "MyClient/1.0.0";
        $r                          = GuzzleHttp::GuzzleGetNew(Status::LINK_FLOW["url"] . "token", 2, $header);
        if ($r['code'] == 200) {
            $token = json_decode($r["contents"], true);
            return $token["token"];
        }
        return "";
    }

}
